/**
 * file: router.js
 * description: 路由加载器
 * author : [" t_fate@163.com "]
 * date : 2014/3/7
 */
'use strict';

var fs = require('fs');

module.exports = function(){
    var app = arguments[0];
    // 读取routers文件夹下面所有的路由配置[全部为同步读取]
    console.log('路由初始化...');
    var files = fs.readdirSync(__dirname + '/routers/');
    for(var i in files){
        var stat = fs.statSync(__dirname + '/routers/'+files[i]);
        if(stat.isDirectory()){
            continue;
        } 
        var fileData = JSON.parse(fs.readFileSync(__dirname + '/routers/'+files[i],'utf-8'));
        for(var routerName in fileData){
            var vArr = fileData[routerName].split('.');
            // 检查模块文件是否存在 
            var mPath = __dirname + '/controls/' + vArr[0] + '.js';
            if(fs.existsSync(mPath)){
              // 载入对应控制器
              var Ctr = require(__dirname + '/controls/' + vArr[0] + '.js');
              app.all(routerName,Ctr[vArr[1]]);
            }else{
              console.log(vArr[0] + ' controls does not exist!');
            }
        }
    }
}

